package nettyProtocol.handshakeAndAuthentication;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import nettyProtocol.pojo.Header;
import nettyProtocol.pojo.NettyMessage;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ChannelHandler.Sharable
public class LoginAuthRespHandler extends ChannelInboundHandlerAdapter {
    private Map<String,Boolean> nodeCheck = new ConcurrentHashMap<String, Boolean>();
    //白名单
    private String[] whitekList = {"/127.0.0.1","/192.168.77.1"};

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMessage message = (NettyMessage) msg;
        //如果是握手请求消息，处理
        if(message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_REQ.value){
            System.out.println("服务端收到握手请求:"+message);
            String nodeIndex = ctx.channel().remoteAddress().toString();
            NettyMessage loginResp = null;
            //重复登录，拒绝
            if(nodeCheck.containsKey(nodeIndex)){
                loginResp = buildResponse("login_repeat");
            } else {
                InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
                String ip = address.getAddress().getHostAddress();
                boolean isOK = false;
                for (String WIP :
                        whitekList) {
                    if(WIP.equals(ip)) {
                        isOK = true;
                        break;
                    }
                }
                loginResp = isOK ? buildResponse("login_ok") : buildResponse("login_fail");
                if(isOK) nodeCheck.put(nodeIndex, true);
                System.out.println("The login response is :" + loginResp + "body[" + loginResp.getBody() + "]");
                //发送回复
                ctx.writeAndFlush(loginResp);
            }
        }else {
            ctx.fireChannelRead(msg);
        }
    }

    private NettyMessage buildResponse(String  result) {

        NettyMessage message = new NettyMessage();
        Header header = new Header();
        header.setType(MessageType.LOGIN_RESP.value);
        message.setHeader(header);
        message.setBody(result);
        return message;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("LoginAuthRespHandler");
        nodeCheck.remove(ctx.channel().remoteAddress().toString()); //删除缓存
        ctx.close();
        ctx.fireExceptionCaught(cause);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
}
